package com.ucs.daoDbImpl;

import java.io.InputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class SqlMapUtil {
	private static final Map<String, SqlMapClient> sqlMapClients = new HashMap<String, SqlMapClient>();
	static {
		InputStream is1 = Thread.currentThread().getContextClassLoader().getResourceAsStream("SqlMapConfig_admin.xml");
		SqlMapClient sqlMapClient1 = SqlMapClientBuilder.buildSqlMapClient(is1);
		sqlMapClients.put("ucs_admin", sqlMapClient1);
		
		InputStream is2 = Thread.currentThread().getContextClassLoader().getResourceAsStream("SqlMapConfig_food.xml");
		SqlMapClient sqlMapClient2 = SqlMapClientBuilder.buildSqlMapClient(is2);
		sqlMapClients.put("ucs_food", sqlMapClient2);
		
		InputStream is3 = Thread.currentThread().getContextClassLoader().getResourceAsStream("SqlMapConfig_order.xml");
		SqlMapClient sqlMapClient3 = SqlMapClientBuilder.buildSqlMapClient(is3);
		sqlMapClients.put("ucs_order", sqlMapClient3);		
	}
	
	public static SqlMapClient getSqlMapClient(String dbname){
		return sqlMapClients.get(dbname);
	}

	public static Connection getDbConnection(String dbname){
		try {
			return sqlMapClients.get(dbname).getCurrentConnection();			
		} catch (Exception e) {
			throw new UCSException("Could not retrieve connection for database: "+dbname, e);
		}
	}
	
	public static JdbcTemplate getJdbcTemplate(String dbname){
		return new JdbcTemplate(sqlMapClients.get(dbname).getDataSource());
	}
	
	public static SimpleJdbcTemplate getSimpleJdbcTemplate(String dbname){
		return new SimpleJdbcTemplate(sqlMapClients.get(dbname).getDataSource());
	}
	
}
